# coding: UTF-8

import os
import re
import base64

from IResolve import IResolve
from YTSTools import file
from YTSTools import convert
from ResolverModuleAction import ResolverModuleAction

class Resolve_Source_Markdown(IResolve):
    def __init__(self, Blog, FileInfo):
        IResolve.__init__(self, Blog, FileInfo)
        self.data = None
        self.rewritefilepath = None
        self.moduleAction = ResolverModuleAction()

    def IsReWrite(self):
        return True

    def ReWriteFilePath(self):
        if self.rewritefilepath is None:
            targetPath = self.FileInfo.get('targetFilePath', None)
            if not targetPath:
                return None
            self.rewritefilepath = self.ChangeExtensionName(targetPath, '.html')
        return self.rewritefilepath

    def ChangeExtensionName(self, targetPath, newExtensionName):
        (pdir, pfile) = os.path.split(targetPath)
        (name, extension) = os.path.splitext(pfile)
        path = os.path.join(pdir, name + newExtensionName)
        return path

    def ReWriteContent(self):
        spath = self.FileInfo.get('sourceFilePath')
        if not spath:
            return None
        markdownContent = file.file_read(spath)
        temp_path = os.path.join(self.Blog.template, "_posts/article_markdown.html")
        temp_path = os.path.abspath(temp_path)
        templateContent = file.file_read(temp_path)
        return self.FillTemplateContent(templateContent, markdownContent)

    def FillTemplateContent(self, templateContent, markdownContent):
        def callback(module, args):
            if module == 'article':
                if args == 'content':
                    return markdownContent
                elif args == 'base64Content':
                    return base64.b64encode(markdownContent.encode())
                return self.moduleAction.dict_extract_value(self.Data(), args, None)
            info = self.Blog.project.get('info', {})
            data = info.get(module, {})
            return self.moduleAction.dict_extract_value(data, args, None)
        return self.moduleAction.Method(templateContent, callback)

    def FileType(self):
        return 'article'

    def Data(self):
        if self.data is None:
            (modify_time, create_time) = self.article_modify_times()
            spath = self.FileInfo.get('sourceFilePath')
            if not spath:
                return None
            markdownContent = file.file_read(spath)
            self.data = {
                "path": self.article_relatively_path(),
                "title": self.article_title(markdownContent),
                "keyworks": '',
                "description": self.article_description(markdownContent),
                "modify_time": modify_time,
                "create_time": create_time,
            }
        return self.data

    def article_relatively_path(self):
        rpath = self.FileInfo.get('targetFilePath')
        rpath = self.ReWriteFilePath()
        rpath = rpath.replace(self.Blog.target, '')
        rpath = rpath.replace('\\', '/')
        rpath = convert.trim(rpath, r'[\\/]+')

        info = self.Blog.project.get('info', {})
        root = info.get('site', {}).get('root', '')
        root = convert.trimEnd(root, r'[\\/]+')
        rpath = root + '/' + rpath
        return rpath

    def article_modify_times(self):
        os.chdir(self.Blog.source)
        spath = self.FileInfo.get('sourceFilePath')
        rpath = spath.replace(self.Blog.source, '')
        rpath = rpath.replace('\\', '/')
        rpath = convert.trim(rpath, r'[\\/]+')
        cmd = "git log --date-order --pretty=format:'time(%ct)' \"{}\"".format(rpath)
        result = convert.execute_command(cmd)
        pattern = re.compile(r'time\((\d+)\)')
        rlist = pattern.findall(result)
        lencount = len(rlist)
        if lencount > 0:
            modify_time = int(rlist[0])
            create_time = int(rlist[lencount-1])
        else:
            fileinfo = os.stat(spath)
            modify_time = fileinfo.st_mtime
            create_time = fileinfo.st_ctime
        def get_time(timestamp):
            import datetime
            return datetime.datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
        return (get_time(modify_time), get_time(create_time))

    def article_title(self, content):
        title = ''
        result = re.search(r'\s*\#+\s*([^\n]+)', content)
        if result:
            title = result.groups()[0]
        return title

    def article_description(self, content):
        description = ''
        result = re.search(r'^([^\#\`\*\[\s][^\n]+)', content, re.M)
        if result:
            description = result.groups()[0]
            description = re.sub(r'[\#\`\*\[\s\>]', '', description)
        return description
